#!/bin/bash

# 分布式存储系统 - 停止ChunkServer脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== 分布式存储系统 - 停止ChunkServer脚本 ===${NC}"
echo ""

# 查找并停止所有chunkserver进程
echo -e "${YELLOW}查找chunkserver进程...${NC}"
CHUNKSERVER_PIDS=$(pgrep -f "chunkserver_server")

if [ -z "$CHUNKSERVER_PIDS" ]; then
    echo -e "${YELLOW}没有找到运行中的chunkserver进程${NC}"
    exit 0
fi

echo -e "${YELLOW}找到以下chunkserver进程:${NC}"
echo "$CHUNKSERVER_PIDS"

echo ""
echo -e "${YELLOW}正在停止chunkserver进程...${NC}"

# 发送SIGTERM信号
for PID in $CHUNKSERVER_PIDS; do
    echo -e "${BLUE}停止进程 $PID...${NC}"
    kill $PID
done

# 等待进程结束
sleep 3

# 检查是否还有进程在运行
REMAINING_PIDS=$(pgrep -f "chunkserver_server")
if [ -n "$REMAINING_PIDS" ]; then
    echo -e "${YELLOW}部分进程仍在运行，发送SIGKILL信号...${NC}"
    for PID in $REMAINING_PIDS; do
        echo -e "${RED}强制停止进程 $PID...${NC}"
        kill -9 $PID
    done
    sleep 1
fi

# 最终检查
FINAL_CHECK=$(pgrep -f "chunkserver_server")
if [ -z "$FINAL_CHECK" ]; then
    echo -e "${GREEN}✓ 所有chunkserver进程已成功停止${NC}"
else
    echo -e "${RED}✗ 仍有chunkserver进程在运行: $FINAL_CHECK${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}=== 停止完成 ===${NC}" 